import socket
from socket import *


class Client:
    def __init__(self, userId, socket_object, server_host_port=("192.168.1.7", 9999)):
        self.address = ""
        self.port = 0
        self.socket = socket_object
        self.server_host_port = server_host_port
        self.userId = userId

    def get_ip(self):
        self.socket.connect(("8.8.8.8", 80))
        ip = self.socket.getsockname()[0]
        self.address = ip

    def get_port(self):
        for i in range(1, 50000):
            s = socket(AF_INET, SOCK_DGRAM)
            if s.connect_ex((self.address, i)) == 0:
                self.port = i
                return
            s.close()

    # 通知服务器 我已经上线了 发送我的Ip和端口
    def online_massage(self, port=0):
        self.get_ip()
        self.get_port()
        if port:
            self.port = port
        online_port = f"online||{self.userId}::{self.address}::{self.port}".encode("utf-8")
        self.socket.sendto(online_port, self.server_host_port)

    # 发送消息给指定ip的指定port
    def send_massage_by_server(self, notice, userId):
        str = ""
        for i in notice:
            str += i+" "
        str = str.strip()
        notice = f"send_massage||{userId}::{str}".encode("utf-8")
        # massage_to_server = (to_user_port, massage)
        self.socket.sendto(notice, self.server_host_port)

    def send_massage_by_local(self, notice, to_user_port):
        notice = f"{self.userId}::{notice}".encode("utf-8")
        self.socket.sendto(notice, to_user_port)


if __name__ == "__main__":
    socket_object = socket(AF_INET, SOCK_DGRAM)
    client_server = Client(input("昵称:"), socket_object)
    client_server.online_massage()
    while True:
        massage = input("Massage:")
        massage = massage.split(" ")
        client_server.send_massage_by_server(massage[1:], massage[0])
